<?php
class PlayerInfo extends Model {
  public function  __construct() {
    parent::Model();
  }

  public function create($data) {
    foreach ($data as $key => $value) {
      $this->db->set($key, $value);
    }
    $query = $this->db->insert(PLAYERINFO_TABLENAME);

    if(!$query) {
      log_message('error','Error during arena creation! SQL: '.$this->db->insert_string());
      return FALSE;
    } else {
      $id = $this->db->insert_id();
      log_message('info','Arena ('.$id.') was inserted to the database!');
      return $id;
    }
  }

  public function read($id) {
    $this->db->where('id',$id);
    $query = $this->db->get(PLAYERINFO_TABLENAME);

    if(!$query || $query->num_rows() != 1) {
      log_message('error','Error during arena read! SQL: '.$this->db->last_query());
      return FALSE;
    } else {
      log_message('info','Arena ('.$id.') was read from the database!');
      return $query->row_array();
    }
  }

  public function update($id, $data) {
    $old = $this->read($id);
    $histories = array();
    $isUpdate = FALSE;
    foreach ($data as $key => $value) {
      if ($old[$key] != $value) {
        $isUpdate = TRUE;
        $colHist = array('columnName' => $key,'oldValue' => $old[$key], 'newValue' => $value);
        $this->db->set($key, $value);
        array_push($histories, $colHist);
      }
    }
    if ($isUpdate) {
      $this->db->where('id',$id);
      $query = $this->db->update(PLAYERINFO_TABLENAME);

      if(!$query || $this->db->affected_rows() != 1) {
        log_message('error','Error during arena update! SQL: '.$this->db->update_string());
        return FALSE;
      } else {
        foreach ($histories as $history) {
          $this->db->set('table',PLAYERINFO_TABLENAME);
          $this->db->set('recordId',$id);
          $this->db->set('columnName',$history['columnName']);
          $this->db->set('oldValue',$history['oldValue']);
          $this->db->set('newValue',$history['newValue']);
          $this->db->insert('history');
        }

        log_message('info','Arena ('.$id.') was updated in the database!');
        return TRUE;
      }
    }
    return TRUE;
  }

  public function delete($id) {
    $this->db->where('id', $id);
    $query = $this->db->delete(PLAYERINFO_TABLENAME);

    if(!$query || $this->db->affected_rows() != 0) {
      log_message('error','Error during arena delete! SQL: '.$this->db->last_query());
      return FALSE;
    } else {
      log_message('info','Arena ('.$id.') was deleted from the database!');
      return TRUE;
    }
  }
}
?>